<?php

	include_once '../controladores/ControladorAplicaciones.php';
	include_once '../controladores/ControladorUsuarios.php';
	include_once '../controladores/ControladorImagenes.php';
	include_once "../config.inc.php";
	include_once '../controladores/ControladorElementos.php';
	
			$usr = $_GET['usr'];
			$app = $_GET['app'];
			$secc = $_GET['sec'];
			$elm = $_GET['elm'];
	
	isset($_FILES['files']["name"]) ? $nameFile = $_FILES['files']["name"] : $nameFile = 0;
	
	// Obteniendo datos del usuario, nada que ver con insercion de elementos.
	
	if ($nameFile != 0){
		
		$command = new ControladorAplicaciones();	
		$appName = $command->searchApplicationName($app);
		$command = new ControladorUsuarios();
		$userEmail = $command->obtainUserEmail($usr);
	
		$targetApplication = ROUTE_APPLICATIONS_USERS.$userEmail."/Applications/".$appName;
		$targetApplicationImages = $targetApplication."/images";
		
		$nameFile = $_FILES['files']["name"];
		$targets = array();	
		$ids = array();	
			
			for ($i=0; $i < count($nameFile); $i++){		
				
				$command = new ControladorImagenes();	
				$im = $command->searchImageId(basename($nameFile[$i]));
				$targets[$i] = $targetApplicationImages."/".basename($nameFile[$i]); 
				
				  if (strlen($im) == 0){
					  
					$command->createImage(basename($nameFile[$i]));
					$im = $command->searchImageId(basename($nameFile[$i]));
					$ids[$i] = $im;								
					
				  }
				  else{ 
				  
					$im = $command->searchImageId(basename($nameFile[$i]));
					$ids[$i] = $im;								
					
				  }
			}
	
		$locations = array();
		
		  $tmpLocations = $_FILES['files']["tmp_name"];		
								
			for ($i=0; $i < count($tmpLocations); $i++) 
					$locations[$i] =  $tmpLocations[$i];
	
		//---------------------------------------------------------------------------------------------
		
		$command = new ControladorElementos(IMAGE_ELEMENT);
			
		  for ($i=0; $i < count($locations); $i++){
			if (move_uploaded_file($locations[$i],$targets[$i])){
				$command->createElement(array("image_id" => $ids[$i],"sec_id" => $secc,"element_order" => ($i+1),"ie_link_to" => "","gallery_id" => $elm));
			}
		  }
	}
	
  	header("Location:section_elements.php?usr=".$usr."&app=".$app."&sec=".$secc."");
?>